package com.itqf.dao.impl;

import com.itqf.connecter.DbConnection;
import com.itqf.dao.UserDao;
import com.itqf.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {

    @Override
    public User selectUserByUsername(String username) throws SQLException {


        Connection conn=null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = null;
        conn= DbConnection.getConnection();
        User user  = null;
        try {
            sql = "select userno as userno , userpassword as userpassword , username as username , sex as sex , e_mail as email , occupation as occupation ,status as status,u_code as ucode from user WHERE  username = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            while (rs.next()) {
                int userno = rs.getInt(1);
                String userpassword = rs.getString(2);
                String sex = rs.getString(4);
                String email = rs.getString(5);
                int occupation = rs.getInt(6);
                int status = rs.getInt(7);
                String u_code = rs.getString(8);
                user = new User(userno,userpassword,username,sex,email,occupation,status,u_code);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally{
            DbConnection.close(rs, ps);
        }
        System.out.println(user.toString());
        return user;
    }

    @Override
    public int insertUser(User user) throws SQLException {
        Connection conn=null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = null;
        int rows = 0;
        conn= DbConnection.getConnection();
        sql ="insert into user (username,userpassword,sex,e_mail,occupation,status,u_code) value(?,?,?,?,?,?,?)";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            System.out.println(user.getUserpassword());
            ps.setString(2, user.getUserpassword());
            ps.setString(3, user.getSex());
            ps.setString(4, user.getEmail());
            ps.setInt(5, user.getOccupation());
            ps.setInt(6, user.getStatus());
            ps.setString(7, user.getUcode());
            rows = ps.executeUpdate();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        DbConnection.close(rs, ps);
        return rows;
    }
}
